from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier

# 加载数据集
iris = load_iris()
X, y = iris.data, iris.target

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 特征缩放
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 定义KNN模型
knn = KNeighborsClassifier()

# 设置网格搜索参数
param_grid = {'n_neighbors': [1, 3, 5, 7, 9]}

# 初始化网格搜索对象
grid_search = GridSearchCV(estimator=knn, param_grid=param_grid, cv=5)

# 执行网格搜索
grid_search.fit(X_train, y_train)

# 获取最优参数和模型
best_params = grid_search.best_params_
best_model = grid_search.best_estimator_

# 模型评估
score = best_model.score(X_test, y_test)
print(f"最优参数: {best_params}")
print(f"测试集准确率: {score}")